import type { MiddlewareHandler, Context } from 'hono'
import { RateLimitError } from '@/middleware/errorHandler'
import { cache } from '@/lib/redis'
import { config } from '@/config/env'

// 限流中间件
export const rateLimiter = (options?: {
  windowMs?: number
  maxRequests?: number
  keyGenerator?: (c: Context) => string
}): MiddlewareHandler => {
  const windowMs = options?.windowMs || config.security.rateLimitWindowMs
  const maxRequests = options?.maxRequests || config.security.rateLimitMaxRequests
  const keyGenerator = options?.keyGenerator || ((c: Context) => {
    // 默认使用IP地址作为限流键
    return `rate_limit:${c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown'}`
  })

  return async (c, next) => {
    const key = keyGenerator(c)
    const window = Math.floor(Date.now() / windowMs)
    const cacheKey = `${key}:${window}`

    try {
      // 获取当前窗口的请求次数
      const current = await cache.incr(cacheKey)
      
      // 设置过期时间（秒）
      if (current === 1) {
        await cache.expire(cacheKey, Math.ceil(windowMs / 1000))
      }

      // 检查是否超过限制
      if (current > maxRequests) {
        throw new RateLimitError(`Too many requests. Limit: ${maxRequests} per ${windowMs}ms`)
      }

      // 设置响应头
      c.header('X-RateLimit-Limit', maxRequests.toString())
      c.header('X-RateLimit-Remaining', Math.max(0, maxRequests - current).toString())
      c.header('X-RateLimit-Reset', (Date.now() + windowMs).toString())

      await next()
    } catch (error) {
      if (error instanceof RateLimitError) {
        throw error
      }
      // Redis 错误时不阻塞请求
      console.warn('Rate limiter error:', error)
      await next()
    }
  }
}
